package unit14.future;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class MatchCounter implements Callable<Integer>{
	private File directory;
	private String keyword;
	private int count;
	
	public MatchCounter(File file, String keyword2) {
		// TODO Auto-generated constructor stub
		this.directory=file;
		this.keyword=keyword2;
	}

	@Override
	public Integer call() throws Exception {
		// TODO Auto-generated method stub
		count=0;
		try {
			File[] files=directory.listFiles();
			List<Future<Integer>> results=new ArrayList<>();
			for(File file:files)
				if(file.isDirectory()){
				MatchCounter counter=new MatchCounter(file,keyword);
				FutureTask<Integer> task=new FutureTask<>(counter);
				results.add(task);
				Thread t=new Thread(task);
				t.start();
			}else{
				if(search(file))
					count++;
			}
		for(Future<Integer> result:results){
			try {
				count+=result.get();
			} catch (ExecutionException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		} catch (InterruptedException e) {
			// TODO: handle exception
		}
		return count;
	}

	private boolean search(File file) {
		// TODO Auto-generated method stub
		try {
			try (Scanner in=new Scanner(file)){
				boolean found=false;
				while(!found&&in.hasNextLine()){
					String line=in.nextLine();
					if(line.contains(keyword))
						found=true;
				}
				return found;
			}
		} catch (IOException e) {
			// TODO: handle exception
		}
		return false;
	}

}
